package vip.kqsy.cloud.ai.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.kqsy.cloud.ai.server.mapper.AiSessionMapper;
import vip.kqsy.cloud.ai.server.pojo.dto.SessionAddDTO;
import vip.kqsy.cloud.ai.server.pojo.entity.AiSession;
import vip.kqsy.cloud.ai.server.pojo.entity.AiSessionHistory;
import vip.kqsy.cloud.ai.server.pojo.vo.UserSessionDTO;
import vip.kqsy.cloud.ai.server.service.AiSessionHistoryService;
import vip.kqsy.cloud.ai.server.service.AiSessionService;
import vip.kqsy.cloud.core.common.exception.BizException;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 聊天上下文 服务实现类
 * </p>
 *
 * @author cenjunjie
 * @since 2023-07-08
 */
@Service
@RequiredArgsConstructor
public class AiSessionServiceImpl extends ServiceImpl<AiSessionMapper, AiSession> implements AiSessionService {

    private final AiSessionHistoryService aiSessionHistoryService;

    @Override
    public Long add(SessionAddDTO dto) {
        Long count = lambdaQuery().eq(AiSession::getUserId, dto.getUserId()).count();
        if (count >= 5) {
            throw new BizException("你已超出会话数量限制");
        }

        AiSession aiSession = BeanUtil.toBean(dto, AiSession.class);
        aiSession.setCreateTime(LocalDateTime.now());
        this.save(aiSession);
        return aiSession.getId();
    }

    @Override
    public List<UserSessionDTO> listByUerId(Long userId) {
        List<AiSession> list = lambdaQuery().eq(AiSession::getUserId, userId).list();
        return BeanUtil.copyToList(list, UserSessionDTO.class);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        this.removeById(id);
        aiSessionHistoryService.remove(new LambdaQueryWrapper<AiSessionHistory>().eq(AiSessionHistory::getSessionId, id));
    }
}
